import React, { Component } from 'react';
import moment from 'moment'; //time格式工厂
import style from './TenantManage.less';
import { connect } from 'dva';
import { FormattedMessage, formatMessage } from 'umi/locale'; //此方法引入的数据可以在src/locales中配置
import {
  Input,
  DatePicker,
  Form,
  Row,
  Col,
  Card,
  PageHeader,
  Alert,
  Upload,
  message,
  Icon,
} from 'antd';
import {Select,Button , Table ,Modal,Pagination} from '@/components/CustomAntd'

//日期插件
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';

//表单
const FormItem = Form.Item;
const { TextArea } = Input;

//所属租户选择框
const Option = Select.Option;

//命名空间
const namespace = 'TenantManage';

const mapDispatchToProps = function(dispatch) {
  return {
    dispatch: dispatch,
  };
};

@connect(mapDispatchToProps)
@Form.create()
class ModalBox extends Component {
  constructor(props) {
    super(props);
  }

  state ={
    //确定按钮状态
    loading: false,
  }

  //点击新建，编辑后的回调方法
  onOk = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        //时间处理
        if (values.start_time) {
          values.start_time = moment(values.start_time).format('YYYY-MM-DD 00:00:00');
        }
        if (values.end_time) {
          values.end_time = moment(values.end_time).format('YYYY-MM-DD 23:59:59');
        }
        //租户类型判断
        if (values.tenant_type) {
          if (values.tenant_type === `${formatMessage({
            id: 'iot.tenantmanage.tenantmanage_modal.tenant_yh',
          })}`) {
            values.tenant_type = 1;
          }
          if (values.tenant_type === `${formatMessage({
            id: 'iot.tenantmanage.tenantmanage_modal.tenant_yy',
          })}`) {
            values.tenant_type = 2;
          }
        }
      } else {
        return false;
      }

      if (this.props.modalFlag === 'new') {
        //避免重复点击确定按钮
        this.setState({
          loading: true,
        });
        this.loadingTimer = setTimeout(() => {
          this.setState({
            loading: false,
          });
        }, 1000);
        //重置表单
        this.props.form.resetFields();

        //新增表单请求
        this.props.dispatch({
          type: `${namespace}/addBegin`,
          payload: {
            values: values,
          },
          callback: res => {
            if (res.return_code === 'SUCCESS') {
              //关闭模态框
              this.props.childModalChangeModalState({
                visible: true,
              });
              message.success('新增成功');
              try {
                //代入当前分页状态重新查询一次
                this.props.dispatch({
                  type: `${namespace}/selectBegin`,
                  payload: {
                    page_size: this.props.page_size,
                    page_num: 1,
                    // ...values,
                  },
                });
                //页码状态同步复位 清空搜索表单状态
                this.props.clearSearchForm();
              } catch (err) {
                console.log(err);
              }
            } else {
              //带入当前状态重新查询
              this.props.dispatch({
                type: `${namespace}/selectBegin`,
                payload: {
                  page_size: this.props.page_size,
                  page_num: this.props.page_num,
                  ...this.props.searchFormNow,
                },
              });
            }
          },
        });
      }
      if (this.props.modalFlag === 'edit') {
        //避免重复点击确定按钮
        this.setState({
          loading: true,
        });
        this.loadingTimer = setTimeout(() => {
          this.setState({
            loading: false,
          });
        }, 1000);
        //修改表单请求
        const params = {
          ...this.props.searchFormNow,
        }
        if (params && params.create_time && params.create_time.length > 0) {
          params.created_time_from = moment(params.create_time[0]).format('YYYY-MM-DD HH:mm:00');
          params.created_time_to = moment(params.create_time[1]).format('YYYY-MM-DD HH:mm:59');
        } else {
          delete params.create_time
        }
        delete params.create_time
        this.props.dispatch({
          type: `${namespace}/editBegin`,
          payload: {
            values: values,
            tenant_id: this.props.nowRow.tenant_id,
          },
          callback: res => {
            if (res.return_code === 'SUCCESS') {
              //重置表单
              this.props.form.resetFields();

              this.props.childModalChangeModalState({
                visible: true,
              });

              message.success('修改成功');

              //代入当前分页状态重新查询一次
              this.props.dispatch({
                type: `${namespace}/selectBegin`,
                payload: {
                  page_size: this.props.page_size,
                  page_num: this.props.page_num,
                  ...params,
                },
              });
            }
          },
        });
      }
    });
  };
  getContent =()=>{
    const {
      form: { getFieldDecorator, getFieldValue, getFieldsValue, setFieldsValue, resetFields },
      nowRow,
    } = this.props;
    const tenant_name_rules = {
      rules: [
        {
          required: true,
          message: `${formatMessage({
            id: 'iot.tenantmanage.tenantmanage_modal.tenant_name',
          })}必须填写`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能在这里使用空格',
        },
        {
          min: 0,
          max: 20,
          message: `${formatMessage({
            id: 'iot.tenantmanage.tenantmanage_modal.tenant_name',
          })}不该超过20个字符`,
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.tenant_name
          ? nowRow.tenant_name
          : undefined,
    };
    const tenant_abbr_rules = {
      rules: [
        {
          min: 0,
          max: 20,
          message: `简称不该超过20个字符`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能在这里使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.tenant_abbr
          ? nowRow.tenant_abbr
          : undefined,
    };
    const contact_rules = {
      rules: [
        {
          min: 0,
          max: 20,
          message: `联系人不该超过20个字符`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能在这里使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.contact
          ? nowRow.contact
          : undefined,
    };
    const contact_num_rules = {
      rules: [
        {
          pattern: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/,
          message: '不是一个合法的手机号码',
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.contact_num
          ? nowRow.contact_num
          : undefined,
    };
    const addr_rules = {
      rules: [
        {
          min: 0,
          max: 100,
          message: `地址不该超过100个字符`,
        },
        {
          pattern: /^[^ ]+$/,
          whitespace: true,
          message: '不能在这里使用空格',
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.addr
          ? nowRow.addr
          : undefined,
    };

    const tenant_type_rules = {
      rules: [
        {
          required: true,
          message: `${formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_type' })}必须选择一项`,
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.tenant_type
          ? nowRow.tenant_type == 1
            ? formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yh' })
            : formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yy' })
          : undefined,
    };
    const description_rules = {
      rules: [
        {
          min: 0,
          max: 500,
          message: `描述不该超过500个字符`,
        },
      ],
      initialValue:
        this.props.modalFlag === 'new'
          ? undefined
          : nowRow && nowRow.description
          ? nowRow.description
          : undefined,
    };
    if(this.props.modalFlag === 'detail'){
      //return content;
      return <div style={{marginLeft : 35}}>
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_name' })}：
              {nowRow['tenant_name']}
            </p>
          </div>
        </div>
        {/* 行2 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_abbr' })}：  {nowRow['tenant_abbr']}
            </p>
          </div>
        </div>
        {/* 行3 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.contact' })}： {nowRow['contact']}
            </p>

          </div>
        </div>
        {/* 行4 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.contact_num' })}：{nowRow['contact_num']}
            </p>
          </div>
        </div>
        {/* 行5 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.addr' })}：{nowRow['addr']}
            </p>
          </div>
        </div>
        {/* 行6 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p >

              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_type' })}：
              {
                nowRow['tenant_type'] === 1 ?
                formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yh' }) :
                  nowRow['tenant_type'] === 2 ?
                    formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yy' }) : ''
              }
            </p>
          </div>
        </div>
        {/* 文本 */}
        <div className={style['motal-line']} style={{ height: 100 }}>
          <p >
            {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.description' })}：{nowRow['description']}
          </p>
        </div>
      </div>
    }else{
      return <Form onSubmit={this.query} layout="inline">
        {/* 行1 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              <span className={style.star}>*</span>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_name' })}：

            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('tenant_name', tenant_name_rules)(
                <Input className={style['input-box']} />
              )}
            </Form.Item>
          </div>
        </div>
        {/* 行2 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_abbr' })}：
            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('tenant_abbr', tenant_abbr_rules)(
                <Input className={style['input-box']} />
              )}
            </Form.Item>
          </div>
        </div>
        {/* 行3 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.contact' })}：
            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('contact', contact_rules)(
                <Input className={style['input-box']} />
              )}
            </Form.Item>
          </div>
        </div>
        {/* 行4 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.contact_num' })}：
            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('contact_num', contact_num_rules)(
                <Input className={style['input-box']} />
              )}
            </Form.Item>
          </div>
        </div>
        {/* 行5 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.addr' })}：
            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('addr', addr_rules)(<Input className={style['input-box']} />)}
            </Form.Item>
          </div>
        </div>
        {/* 行6 */}
        <div className={style['motal-line']}>
          <div className={style['every-block']}>
            <p className={style.p1}>
              <span className={style.star}>*</span>
              {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_type' })}：
            </p>
            <Form.Item style={{ marginBottom: 0 }}>
              {getFieldDecorator('tenant_type', tenant_type_rules)(
                <Select className={style['input-box']} placeholder="请选择">
                  <Option value="1">
                    {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yh' })}
                  </Option>
                  <Option value="2">
                    {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant_yy' })}
                  </Option>
                </Select>
              )}
            </Form.Item>
          </div>
        </div>
        {/* 文本 */}
        <div className={style['motal-line']} style={{ height: 100 }}>
          <p className={style.p2}>
            {formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.description' })}：
          </p>
          <Form.Item style={{ marginBottom: 0 }}>
            {getFieldDecorator('description', description_rules)(
              <TextArea rows={4} style={{ float: 'left', width: 620 }} />
            )}
          </Form.Item>
        </div>
      </Form>;
    }
  }
  componentWillUnmount(){
    //清除定时器，防止内存泄露
    clearTimeout(this.loadingTimer);
  }

  render() {
    const { dispatch, form } = this.props;
    const {
      form: { getFieldDecorator, getFieldValue, getFieldsValue, setFieldsValue, resetFields },
      nowRow,
    } = this.props;

    return (
      <div>
        <Modal
          visible={this.props.visible}
          title={`${
            this.props.modalFlag === 'new'
              ?  formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.create_tenant' })
              : this.props.modalFlag === 'edit'? formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.edit_tenant' }) :
              formatMessage({ id: 'iot.tenantmanage.tenantmanage_modal.tenant' })
          }`}
          onCancel={this.props.cancel}
          destroyOnClose={true}
          maskClosable={false}
          bodyStyle={{
            width: 800,
          }}
          width="800px"
          onOk={this.onOk}
          page_size={this.props.page_size}
          footer={
              this.props.modalFlag === 'detail' ?
                [
                  <Button key="back" type="primary" onClick={this.props.cancel}>
                    确定
                  </Button>
                ]
              :
              [
              <Button key="back" onClick={this.props.cancel}>
                取消
              </Button>,
              <Button
                key="submit"
                type="primary"
                loading={this.state.loading}
                onClick={this.onOk}
              >
                提交
              </Button>,
            ]
          }
        >
          {this.getContent()}
        </Modal>
      </div>
    );
  }
}

export default ModalBox;
